﻿using System;
using EP.Base.BaseService.Manager.Config.Enum;
using EP.Base.BaseService.Manager.Interface;
using EP.Base.BaseService.Manager.Interface.Business;
using EP.Base.BaseService.Manager.Interface.Common;
using EP.Base.BaseService.Manager.Interface.Data;
using EP.Base.BaseService.Manager.Model.Entity;

namespace EP.Base.BaseService.Manager.Business.Task
{
    /// <summary>
    /// 索引备份状态检测任务
    /// </summary>
    public class IndexBackupStateCheckTask : IEsIndexHandelTask
    {
        private readonly IEsClusters _esClusters;
        private readonly IIndexConfigs _indexConfigs;
        private readonly IEsData _esData;
        private readonly ILog _log;
        private readonly IIndexBackupLogs _indexBackupLogs;

        public IndexBackupStateCheckTask(IEsClusters esClusters, IIndexConfigs indexConfigs, IEsData esData, ILog log, IIndexBackupLogs indexBackupLogs)
        {
            _esClusters = esClusters;
            _indexConfigs = indexConfigs;
            _esData = esData;
            _log = log;
            _indexBackupLogs = indexBackupLogs;
        }

        public bool Exec(EsTaskConfig taskConfig)
        {
            _log.Debug("执行索引备份状态检测任务 id=" + taskConfig.Id);

            //index信息
            var indexConfig = _indexConfigs.Get(taskConfig.IndexConfigId);
            if (indexConfig == null)
            {
                _log.WarnFormat("IndexConfigId={0},未找到对应的indexConfig数据！", taskConfig.IndexConfigId);
                return false;
            }
            //es集群信息
            var esClustersInfo = _esClusters.Get(indexConfig.ClusterId);
            if (esClustersInfo == null)
            {
                _log.WarnFormat("ClusterId={0},未找到对应的esClustersInfo数据！", indexConfig.ClusterId);
                return false;
            }
            var baklogs = _indexBackupLogs.GetIndexBackupLogsByIndexConfidId(taskConfig.IndexConfigId,
                (short) EnumIndexBackupLogState.Eexecuted);

            if (baklogs == null)
                return true;
            foreach (var indexBackupLog in baklogs)
            {
                //快照信息
                var result=_esData.GetSnapshotInfo(esClustersInfo.ServiceHostArr, indexBackupLog.Repository,indexBackupLog.SnapshotName);

                if(result==null)
                    continue;
                var state = EnumIndexBackupLogState.Eexecuted;
                //成功
                if (result.State.ToUpper() == "SUCCESS")
                {
                    state = EnumIndexBackupLogState.Success;
                }
                    //失败
                else if (result.State.ToUpper() == "FAILED")
                {
                    state = EnumIndexBackupLogState.BkFail;
                }
                //更新检测结果
                _indexBackupLogs.UpdateStateAndCheckInfo(indexBackupLog.Id, (short) state, DateTime.Now, result.State);
            }

            return true;
        }
    }
}
